<?php
class Xigg_Main_SubmitVote extends Sabai_Controller
{
    function _doExecute(&$context)
    {
        if (!$context->request->isPost()) {
            $context->response->setError(_('Invalid request method'), Sabai_URL::get());
            return;
        }
        require_once 'Sabai/Validator/Token.php';
        if ((!$token_value = $context->request->getAsStr(SABAI_TOKEN_NAME, false)) ||
            (!$node_id = $context->request->getAsInt('node_id', false))) {
            $context->response->setError(_('Invalid request'), Sabai_URL::get());
            return;
        }
        $validator =& new Sabai_Validator_Token('Vote_submit_' . $node_id);
        if (!$validator->validate($token_value)) {
            $context->response->setError(_('Invalid request'), Sabai_URL::get());
            return;
        }
        if (!$node =& $this->_parent->getNodeById($context->request, 'node_id')) {
            $context->response->setError(_('Invalid node'), Sabai_URL::get());
            return;
        }
        $model =& $this->_locator->getService('Model');
        $vote_r =& $model->getRepository('Vote');
        if (0 < $vote_r->countByNodeAndUser($node_id, $context->user)) {
            $context->response->setError(_('Already voted'), Sabai_URL::get('/node/' . $node->getId()));
            return;
        }
        $vote =& $node->createVote();
        $vote->assignUser($context->user);
        if ($ip = $this->_getClientIP()) {
            $vote->set('ip', $ip);
        }
        $vote->set('score', 1);
        $vote->markNew();
        if (!$vote->commit()) {
            $context->response->setError(_('Failed operation'), Sabai_URL::get('/node/' . $node->getId()));
            return;
        }
        $node_votes = $node->countVotes();
        if ($context->request->getAsBool('echo', false)) {
            $msg = $node_votes;
        } else {
            $msg = _('Voted successfully');
        }
        // make the article published if more than required votes
        if ($node_votes > $context->config->get('numberOfVotesForPopular')) {
            $node->published();
        }
        $context->response->setSuccess($msg, Sabai_URL::get('/node/' . $node->getId()));
    }

    function _getClientIP()
    {
        foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR') as $key) {
            if (!empty($_SERVER[$key]) && ($_SERVER[$key] != 'unknown')) {
                return $_SERVER[$key];
            }
        }
        return false;
    }
}